package cn.yunhe.dao;
import java.sql.*;
import java.util.*;
import java.sql.DriverManager;

public class BaseDB {	
	private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
	static{
		try {
			//System.out.println("909090909099909090");
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection(){
		Connection con=null;
		try {
			//System.out.println("**********************");
			con =DriverManager.getConnection(url,"fhs","fhs");
			//System.out.println("-----------------------");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}
	public static void setparams(PreparedStatement ps,Object[]params) throws SQLException{
		if(params==null){
			return ;
		}
		for(int i=0;i<params.length;i++){
			ps.setObject(i+1,params[i]);
		}
	}
	public static void closeAll(ResultSet rs,Statement st,Connection con){
		try {
			if(rs!=null){
				rs.close();
				rs=null;
			}
			if(st!=null){
				st.close();
				st=null;
			}
			if(con!=null){
				con.close();
				con=null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static int executeUpdate(String sql,Object[]params){
		Connection con=null;
		PreparedStatement ps=null;
		try {
			con = getConnection();
			ps = con.prepareStatement(sql);
			setparams(ps,params);
			return ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeAll(null, ps, con);
		}
		return -1;
	}
	public List executeQuery(String sql,Object[]params){
		List table=new ArrayList();
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con = getConnection();
			ps = con.prepareStatement(sql);
			setparams(ps,params);
			rs = ps.executeQuery();
			int count=rs.getMetaData().getColumnCount();
			while(rs.next()){
				List row=new ArrayList();
				for(int i=1;i<=count;i++){
					row.add(rs.getString(i));
				}
				table.add(row);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeAll(rs, ps, con);
		}
		
		return table;
	}
	
}
